import React, { useState } from 'react';
import { Table, Button, Input, Select, Form, Modal, Pagination, Space, message } from 'antd';
import { useEffect } from 'react';
import { api, queryList } from '../api/api';
import Url from '../api/url';

const { Option } = Select;



const columns = [
  // {
  //   title: '',
  //   dataIndex: 'checkbox',
  //   render: (_, record) => (
  //     <Input type="checkbox" checked={record.selected} onChange={() => record.onSelect(record.key)} />
  //   ),
  //   width: 40,
  // },
  { title: '用户名', dataIndex: 'USERID', width: 100 },
  { title: '客户名称', dataIndex: 'CUSTOMER_NAME', width: 200 },
  { title: '对应商品编码', dataIndex: 'PRODNO', width: 140 },
  // { title: '商品名称', dataIndex: 'prodName', width: 120 },
  // { title: '商品规格', dataIndex: 'prodSpec', width: 100 },
  // { title: '包装单位', dataIndex: 'packUnit', width: 80 },
  // { title: '生产厂家', dataIndex: 'factory', width: 200 },
  // { title: '公司标识', dataIndex: 'companyMark', width: 120 },
  // { title: '业务类型', dataIndex: 'bizType', width: 120 },
];



const CustOfProdPage = () => {
  const [data, setData] = useState([]);
  const [selectedKeys, setSelectedKeys] = useState([]);
  const [modalVisible, setModalVisible] = useState(false);
  const [modalType, setModalType] = useState('add'); // add | edit
  const [editingRow, setEditingRow] = useState(null);
  const [form] = Form.useForm();
  const [filters, setFilters] = useState({
      CUSTOMER_NAME: '',
      USERID: '',
      PRODNO: '',
    });
  // const [selectedKeys, setSelectedKeys] = useState([]);

  const pageLoad = async () => {
      const dataList = await queryList({url:Url.custProd,params:filters})
      setData(dataList)
  }

  const search = async () => {
      const dataList = await queryList({url:Url.custProd,params:filters})
      setData(dataList)
  }

   const handleInputChange = (changedValues) => {
    setFilters({ ...filters, ...changedValues });
  };

  // 选择行
  const handleSelect = (key) => {
    setSelectedKeys((prev) =>
      prev.includes(key) ? prev.filter((k) => k !== key) : [...prev, key]
    );
  };

  // 打开添加/编辑弹窗
  const openModal = (type) => {
    setModalType(type);
    if (type === 'add') {
      setEditingRow(null);
    } else if (type === 'edit') {
      if (selectedKeys.length !== 1) {
        message.warning('请选择一条要修改的数据');
        return;
      }
      const row = data.find((item) => item.key === selectedKeys[0]);
      form.setFieldsValue(row);
      setEditingRow(row);
    }
    setModalVisible(true);
  };

  // 添加或编辑提交
  const handleOk = async () => {
    const values = await form.validateFields()
    
     if (modalType === 'add') {
        const newRow = { ...values };
        const res = await api({url:Url.addCustProd,data:newRow})
        message.success(res.msg);
        search()
        // setData([...data, newRow]);
      } else if (modalType === 'edit' && editingRow) {
        setData(
          data.map((item) =>
            item.key === editingRow.key ? { ...editingRow, ...values } : item
          )
        );
        message.success('修改成功');
      }
      setModalVisible(false);
      setEditingRow(null);
      // setSelectedKeys([]);
    
  };

  // 删除
  const handleDelete = () => {
    if (selectedKeys.length === 0) {
      Modal.info({ title: '提示', content: '请先选择要删除的数据' });
      return;
    }
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除选中的数据吗？',
      onOk: async () => {
        const res = await api({url:Url.delCustProd,data:{pkList:selectedKeys}})
        message.success(res.msg);
        setData(data.filter((item) => !selectedKeys.includes(item.PK)));
        // setSelectedKeys([]);
      },
    });
  };


  useEffect(()=>{
    pageLoad()
  },[])

  const rowSelection = {
    selectedKeys,
    onChange: setSelectedKeys,
  };

  // 表格数据加上checkbox控制
  const tableData = data.map((row) => ({
    ...row,
    selected: selectedKeys.includes(row.key),
    onSelect: handleSelect,
  }));

  return (
    <div style={{ background: '#f5f7fa', padding: 16 }}>
      <div style={{ background: '#fff', padding: 16, borderRadius: 6, boxShadow: '0 2px 8px #f0f1f2' }}>
        <h2 style={{ marginBottom: 24 }}>客户对应品种</h2>
        <Form layout="inline" style={{ marginBottom: 16 }} clearOnDestroy
        initialValues={filters}
        onValuesChange={handleInputChange}
        >
          <Form.Item label="客户名称" name="CUSTOMER_NAME">
            <Input placeholder="请输入客户名称" allowClear />
          </Form.Item>
          <Form.Item label="商品编码" name="PRODNO">
            <Input placeholder="请输入商品编码" allowClear />
          </Form.Item>
          <Form.Item label="用户名" name="USERID">
            <Input placeholder="请输入用户名" allowClear />
          </Form.Item>
    
          <Form.Item>
            <Button type="primary" onClick={search}>检索</Button>
          </Form.Item>
        </Form>
        <Space style={{ marginBottom: 16 }}>
          <Button type="primary" onClick={() => openModal('add')}>添加</Button>
          <Button danger onClick={handleDelete}>删除</Button>
          {/* <Button onClick={() => openModal('edit')}>修改</Button> */}
        </Space>
        <Table
          columns={columns}
          dataSource={data}
          pagination={false}
          bordered
          size="small"
          scroll={{ x: 1200 }}
          rowKey={'PK'}
          rowSelection={rowSelection}
        />
        
        <div style={{ marginTop: 16, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <span>显示 {data.length} 条，共 {data.length} 条</span>
          <Pagination  total={data.length} pageSize={20} showSizeChanger={false} />
        </div>
      </div>
      <Modal
        title={modalType === 'add' ? '添加' : '修改'}
        open={modalVisible}
        onOk={handleOk}
        onCancel={() => setModalVisible(false)}
        destroyOnHidden
      >
        <Form form={form} layout="vertical"  clearOnDestroy >
          <Form.Item name="USERID" label="用户名" rules={[{ required: true, message: '请输入用户名' }]}> 
            <Input /> 
            </Form.Item>
          <Form.Item name="PRODNO" label="对应商品编码" rules={[{ required: true, message: '请输入商品编码' }]}> 
            <Input />
             </Form.Item>
         
        </Form>
      </Modal>
    </div>
  );
};

export default CustOfProdPage;